package com.zy.ems.common.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.zy.ems.common.page.PageQuery;
import com.zy.ems.common.page.PageQueryBuilder;
import com.zy.ems.common.page.PaginationResult;
import com.zy.ems.common.util.JsonUtils;
import com.zy.ems.common.util.RequestUtil;
import com.zy.ems.common.util.StringUtils;

/**
 * 分页处理器。
 * 
 * @author Luffy
 *
 */
public final class PagingProcessor {
    /**
     * 分页查询。
     * 
     * @param request
     * @param service
     * @param pagination
     * @return
     */
    public static <V> PaginationResult<V> process(HttpServletRequest request,
            BaseService<?, ?> service) {
        return process(request, service, null, null);
    }

    /**
     * 分页查询。
     * 
     * @param request
     * @param service
     * @param pagination
     * @return
     */
    public static <V> PaginationResult<V> process(HttpServletRequest request,
            BaseService<?, ?> service, IPagination pagination) {
        return process(request, service, pagination, null);
    }

    /**
     * 分页查询。
     * 
     * @param request
     * @param service
     * @param pageStmtUID
     * @return
     */
    public static <V> PaginationResult<V> process(HttpServletRequest request,
            BaseService<?, ?> service, IPagination pagination,
            PageStmtUID pageStmtUID) {
        // 获取查询参数
        Map<String, String> map = RequestUtil.getParameterMap(request);
        // 以q方式传输的参数，其值为json串
        String q = map.get("q");
        if (StringUtils.isNotBlank(q)) {
            map.putAll(JsonUtils.readJson2Map(q, String.class));
        }
        // 自定义参数处理
        if (pagination != null) {
            pagination.processParams(map);
        }
        // 设置分页信息
        int start = Integer.parseInt(map.get("start"));
        int pageSize = Integer.parseInt(map.get("size"));
        PageQuery pageQuery = PageQueryBuilder.instance().offset(start)
                .pageSize(pageSize).build();
        // 分页查询
        PaginationResult<V> result = null;
        if (pageStmtUID != null) {
            result = service.getEntityDao().findPageList(pageStmtUID, map,
                    pageQuery);
        }
        else {
            result = service.getEntityDao().findPageList(map, pageQuery);
        }
        // 自定义分页结果处理
        if (pagination != null) {
            pagination.processPageResult(result);
        }
        return result;
    }

}
